package com.ophiux.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * @desc：token验证<br>
 * @author: hhl<br>
 * @date: 2021年10月22日 下午3:23:46<br>
 */
//@Component
public class TokenFilter implements GlobalFilter,Ordered {

	@Override
	public int getOrder() {
		//设置过滤顺序
		return 0;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//获取token参数
		//http://127.0.0.1:80/member  访问时,不会通过
		String token = exchange.getRequest().getQueryParams().getFirst("token");
		if (token == null || token.isEmpty()) {//验证token规则
			ServerHttpResponse response = exchange.getResponse();
			response.setStatusCode(HttpStatus.BAD_REQUEST);
			String msg = "token not is null ";
			DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
			return response.writeWith(Mono.just(buffer));
		}
		// 使用网关过滤
		return chain.filter(exchange);
	}

}
